package com.rollcall.wisdomroll;

import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.ActivityInfo;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.drawable.Drawable;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;//定义按钮
import android.widget.EditText;//定义文字
import android.widget.TextView;
import android.widget.Toast;

import com.rollcall.wisdomroll.SQLiteDatabase.CreateDB;
import com.rollcall.wisdomroll.SQLiteDatabase.DBManager;
import com.rollcall.wisdomroll.SQLiteDatabase.DatabaseHelper;
import com.rollcall.wisdomroll.SQLiteDatabase.SQLiteOpenHelper;
import com.rollcall.wisdomroll.utils.JumpUtil;
import com.rollcall.wisdomroll.utils.DateUtilsl;
import com.rollcall.wisdomroll.utils.Prefs;
import com.rollcall.wisdomroll.utils.StatusBarUtil;
import com.rollcall.wisdomroll.utils.ToastUtil;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import org.json.JSONException;
import org.json.JSONObject;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;

import okhttp3.Call;
import okhttp3.Response;

public class MainActivity extends AppCompatActivity {
    private Mapp mapp;
    private Button btn_login;//登录按钮id
    private TextView net_settings;//网络设置
    private EditText et_psw;//编辑框id
    private EditText et_user_name;
    private EditText et_xulie;
    private String username;//定义的用户名
    private String password;//定义密码
    private String xulienum;//定义系列号
    private static final String TEMP_INFO="temp_info";
    String shijian;
    String times;
    private SQLiteDatabase db;
    private DatabaseHelper helper;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        StatusBarUtil.setTransparent(this);
        super.onCreate(savedInstanceState);
        //依靠DatabaseHelper的构造函数创建数据库
//        DatabaseHelper dbHelper = new DatabaseHelper(MainActivity.this, "TAB_user", null, 1);
//        db = dbHelper.getWritableDatabase();


        if (!isTaskRoot()) {//解决Android 按home键再次进入是首页界面
            finish();
            return;
        }
        setContentView(R.layout.activity_main);//显示页面]
        //获取数据库对象
        helper= DBManager.getInstance(this);
        SQLiteDatabase db=helper.getWritableDatabase();//创建数据库
        //设置此界面为竖屏
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        init();
        netsettingsview();//跳转网络设置页面

//        btn_login=(Button)findViewById(R.id.btn_login);
//        btn_login.setOnClickListener(new View.OnClickListener() {//点击登录事件
//            @Override
//            public void onClick(View v) {
//                Intent intent=new Intent();
//                intent.setClass(MainActivity.this,NavigationActivity.class);//开启哪个页面
//                startActivity(intent);//开启哪个页面
//                //点一下设备
//
//            }
//
//        });

    }
    //t跳转网络设置页面
    private void netsettingsview(){
        net_settings=(TextView)findViewById(R.id.net_settings);
        net_settings.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                /**
                 * 跳到注册页面RegisterActivity
                 * */
                Intent intent=new Intent();
                intent.setClass(MainActivity.this,netsettings.class);//开启哪个页面
                startActivity(intent);//开启哪个页面
            }
        });

    }
    /**
     * 第二种方式 使用Handler
     *
     */
    private Handler handler=new Handler();
    private void getTime(){
        Timer timer=new Timer();
        TimerTask timerTask=new TimerTask() {
            @Override
            public void run() {
                SimpleDateFormat format=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                Date date = new Date();
                final String times=format.format(new Date());
                handler.post(new Runnable() {
                    @Override
                    public void run() {
                        shijian=times;
                    }
                });
            }
        };
        timer.schedule(timerTask,0,1000);
    }

    //获取界面控件
    private void init() {
        //从main_title_bar中获取的id
//        mapp = (Mapp) getApplication();
        btn_login = findViewById(R.id.btn_login);
        net_settings = findViewById(R.id.net_settings);
        et_user_name = findViewById(R.id.et_user_name);
        et_psw = findViewById(R.id.et_psw);
        SharedPreferences sp = getSharedPreferences(TEMP_INFO, Context.MODE_PRIVATE);
        String content1 = sp.getString("username", "");
        String content2 = sp.getString("password", "");
        et_user_name.setText(content1);
        et_psw.setText(content2);
        getTime();//第二种方法
        //et_xulie = findViewById(R.id.et_xulie);
        //设置输入框的按钮大小（账号）（密码）
        Drawable leftDrawable = et_user_name.getCompoundDrawables()[0];
        if(leftDrawable!=null){
            leftDrawable.setBounds(0, 0, 45, 45);
            et_user_name.setCompoundDrawables(leftDrawable, et_user_name.getCompoundDrawables()[1], et_user_name.getCompoundDrawables()[2], et_user_name.getCompoundDrawables()[3]);
        }
        Drawable leftDrawablep = et_psw.getCompoundDrawables()[0];
        if(leftDrawablep!=null){
            leftDrawablep.setBounds(0, 0, 45, 45);
            et_psw.setCompoundDrawables(leftDrawablep, et_psw.getCompoundDrawables()[1], et_psw.getCompoundDrawables()[2], et_psw.getCompoundDrawables()[3]);
        }
        // 登录按钮的点击事件
        btn_login.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
//                CreateDB db = new CreateDB();
//                db.create();
                //开始登录，获取用户名密码getText().toString().trim();
                username = et_user_name.getText().toString();
                password = et_psw.getText().toString();
                //设置时间格式
                SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss:SSS");
                //得到当前时间
                String currentTime = formatter.format(new Date());
                Date date = null;
                try {
                    date = formatter.parse(currentTime);
                } catch (ParseException e) {
                    e.printStackTrace();
                }

//                xulienum = et_xulie.getText().toString();
                Log.w("tag", "用户名" + username);

               // Log.w("tag", "时间戳" + DateUtilsl.getStringToDate("时间格式",shijian));
                Log.w("tag", "密码" + password);
                if (TextUtils.isEmpty(username)) {//判断为空时
                    Toast.makeText(MainActivity.this, "请输入账号", Toast.LENGTH_SHORT).show();//自带提示
                    return;
                } else if (TextUtils.isEmpty(password)) {
                    Toast.makeText(MainActivity.this, "请输入密码", Toast.LENGTH_SHORT).show();//自带提示
                    return;
                }
//                else if (TextUtils.isEmpty(xulienum)) {
//                    Toast.makeText(MainActivity.this, "请输入序列号", Toast.LENGTH_SHORT).show();//自带提示
//                }
                else {
                    //当前时间戳
                    long ts = date.getTime();
                    Long longObj = new Long(ts);
                    String str = longObj.toString();
                    SharedPreferences preferences=getSharedPreferences("user", Context.MODE_PRIVATE);
                    String fuwIpnum=preferences.getString("fuwIpnum","");
                 //   String duankounum=preferences.getString("duankounum","");
                    System.out.println("是否获取到输入值--"+fuwIpnum);
                  //  System.out.println("是否获取到输入值--"+duankounum);
                    String url = fuwIpnum+"/SyrisFactory/prisonAppDevice/mobileLogin";
                    //String url = "https://www.p7k.top/SyrisFactory/other/AccountPwdLogin";
                    OkHttpUtils.post()
                            .url(url)
                            .addParam("userName",username)
                            .addParam("password",password)
                            .addParam("deviceSn","19847")
//                            .addParam("deviceSn",xulienum)
                            .build()
                            .execute(new StringCallback() {
                                @Override
                                public void onError(Call call, Response response, Exception e, int id) {
                                    //失败
                                    ToastUtil.show(getApplicationContext(),"请求异常,请检查网络或服务器！");
                                    //Log.e("失败了吗",response.toString());
                                }

                                @Override
                                public void onResponse(String response, int id) {
                                    Log.e("###456",response);
                                    try {
                                        JSONObject object = new JSONObject(response);
                                        String ResultStatus = object.getString("flag");
                                        if(ResultStatus.equals("false")){
                                            Log.e("失败了吗170",ResultStatus);
                                            String ResultStatusInfo = object.getString("reason");
                                            ToastUtil.show(getApplicationContext(),ResultStatusInfo);
                                        }else {
                                            String ResultStatusInfo = object.getString("reason");
                                            JSONObject data = object.getJSONObject("user");
                                            String holderName = data.getString("holderName");
                                            String holderNo=data.getString("holderNo");
                                            //获得应用程序实例
                                            Mapp app = (Mapp)getApplicationContext();
                                            //给全局变量赋值
                                            app.setUsername(holderName);
                                            app.setUserno(holderNo);
                                            System.out.println("是否获取到输入值--"+holderName);
                                            JumpUtil.newInstance().jumpRightFlags(getApplicationContext(), NavigationActivity.class);
                                            ToastUtil.show(getApplicationContext(),holderName+"欢迎进入");
                                            //请求接口数据
                                            String url = fuwIpnum+"/SyrisFactory/prisonAppDevice/downLoadPrisoner";
                                            Log.e("tag","登录成功获取时间"+ str);
                                            OkHttpUtils.post()
                                                    .url(url)
                                                    .addParam("updateDate",str)
                                                    .build()
                                                    .execute(new StringCallback() {
                                                        @Override
                                                        public void onError(Call call, Response response, Exception e, int id) {
                                                            //失败
                                                            ToastUtil.show(getApplicationContext(),"请求异常,请检查网络或服务器！");
                                                            //Log.e("失败了吗",response.toString());
                                                        }

                                                        @Override
                                                        public void onResponse(String response, int id) {
                                                            Log.e("###456",response);
                                                            try {
                                                                JSONObject object = new JSONObject(response);
                                                                String ResultStatus = object.getString("flag");
                                                                if(ResultStatus.equals("false")){
                                                                    Log.e("失败了吗170",ResultStatus);
                                                                    String ResultStatusInfo = object.getString("reason");
                                                                    ToastUtil.show(getApplicationContext(),ResultStatusInfo);
                                                                }else {
                                                                    //String ResultStatusInfo = object.getString("reason");
                                                                    JSONObject data = object.getJSONObject("addList");

//                                                                    ContentValues values = new ContentValues();
//                                                                    values.put("prisonerName", "吉珂");
//                                                                    db.insert("TAB_user", null, values);

                                                                }
                                                            } catch (JSONException e) {
                                                                e.printStackTrace();
                                                            }
                                                        }
                                                    });
                                            finish();//跳转成功后关闭前页面不会返回到上一页面
                                        }
                                    } catch (JSONException e) {
                                        e.printStackTrace();
                                    }
                                }
                            });


                }

            }

        });
    }
    protected void onStop(){
        super.onStop();
        SharedPreferences.Editor editor = getSharedPreferences(TEMP_INFO,Context.MODE_PRIVATE).edit();
        editor.putString("username", et_user_name.getText().toString());
        editor.putString("password", et_psw.getText().toString());
        editor.commit();
    }

    }



